/**
 * =========================== 公用js ===========================
 * 需要依赖 constant.js  zepto.min.js  vant.min.js
 */

/**
 * zepto.min.js ajax设置
 */
// if (typeof $ != "undefined") {
//     $.ajaxSettings = $.extend($.ajaxSettings, {
//         xhrFields: {withCredentials: true}, //支持跨域
//         dataType: "json", //返回值为json
//         timeout: 10000,
//         beforeSend: function (xhr, settings) {
//             // console.log('ajax beforeSend...', xhr, settings);
//         },
//         error: function (xhr, errorType, error) {
//             console.log('ajax error...', xhr, errorType, error);
//             //$.hideLoading();
//         }
//     });
//
//     $(document).on('ajaxBeforeSend', function (e, xhr, settings) {
//         if (!/^http(s*):\/\//.test(settings.url)) {
//             settings.url = API.baseUrl + settings.url;
//         }
//     });
// }

/**
 * Date 格式化
 * Date的prototype 属性可以向对象添加属性和方法。
 * @param fmt
 * @returns {void | string | * | boolean}
 * @constructor
 */
Date.prototype.Format = function (fmt) {
  var o = {
    "M+": this.getMonth() + 1,
    "d+": this.getDate(),
    "H+": this.getHours(),
    "m+": this.getMinutes(),
    "s+": this.getSeconds(),
    "S+": this.getMilliseconds()
  };
  //因为date.getFullYear()出来的结果是number类型的,所以为了让结果变成字符串型，下面有两种方法：
  if (/(y+)/.test(fmt)) {
    //第一种：利用字符串连接符“+”给date.getFullYear()+""，加一个空字符串便可以将number类型转换成字符串。
    fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
  }
  for (var k in o) {
    if (new RegExp("(" + k + ")").test(fmt)) {
      //第二种：使用String()类型进行强制数据类型转换String(date.getFullYear())，这种更容易理解。
      fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length)));
    }
  }
  return fmt;
}

/**
 * 获取URL参数
 * @param name
 * @returns {string}
 */
function getUrlParam(name) {
  var result = window.location.search.match(new RegExp("[\?\&]" + name + "=([^\&]+)", "i"));
  if (result == null || result.length < 1 || result[1] == "null" || result[1] == "undefined") {
    return "";
  }
  return decodeURI(decodeURI(result[1]));
}

/**
 * 获取当前文件的一个内存URL
 * @param file
 * @returns {*}
 */
function getObjectURL(file) {
  var url = null;
  if (window.createObjectURL != undefined) { // basic
    url = window.createObjectURL(file);
  } else if (window.URL != undefined) { // mozilla(firefox)
    url = window.URL.createObjectURL(file);
  } else if (window.webkitURL != undefined) { // webkit or chrome
    url = window.webkitURL.createObjectURL(file);
  }
  return url;
}

/**
 * 表单序列话
 * @param form
 */
function serializeForm(form) {
  let formArray = form.serializeArray();
  let params = {};
  if (formArray) {
    formArray.map((item, index) => {
      params[item.name] = item.value;
    });
  }
  return params;
}

/**
 * 获取文件后缀名
 * @param fileName  文件名/文件路径名
 * @returns {string}
 */
function getFileSuffix(fileName) {
  if (!fileName)
    return "";
  let index1 = fileName.lastIndexOf(".");
  let suffix = fileName.substring(index1 + 1, fileName.length);//后缀名
  return suffix;
}

/**
 * 判断一个文件是否是图片格式
 * @param ext
 * @returns {boolean}
 */
function isAssetTypeAnImage(ext) {
  return ['png', 'jpg', 'jpeg', 'bmp', 'gif', 'webp', 'psd', 'svg', 'tiff'].indexOf(ext.toLowerCase()) !== -1;
}

/**
 * 格式化文件大小
 * @param value         文件字节大小
 * @returns {string}    格式化后的文件大小
 */
function renderFileSize(value) {
  if (null == value || value == '') {
    return "0 Bytes";
  }
  let unitArr = new Array("Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB");
  let index = 0;
  let srcSize = parseFloat(value);
  index = Math.floor(Math.log(srcSize) / Math.log(1024));
  let size = srcSize / Math.pow(1024, index);
  //  保留的小数位数
  size = size.toFixed(2);
  return size + unitArr[index];
}

/**
 * 按钮 提交效果
 * @param btn
 */
function btnSubmitCss(btn) {
  btn.css("opacity", ".6");
  btn.text("提交中...")
  btn.attr("disabled", "disabled");
}

/**
 * 按钮 提交失败恢复效果
 * @param btn
 */
function btnRecoverCss(btn) {
  btn.css("opacity", "1");
  btn.text("立即提交");
  btn.remove("disabled");
}


/**
 * 对象是否为空
 * @param object
 * @returns {boolean}
 */
function isEmpty(object) {
  if (object == null || object == "" || object == undefined)
    return true;
  return false;
}


/**
 * 日期工具
 * @type {{function: *}}
 */
var DateUtil = {

  fmt_yyyy_MM: "yyyy-MM",
  fmt_yyyy_MM_dd: "yyyy-MM-dd",
  fmt_yyyy_MM_dd_HH_mm: "yyyy-MM-dd HH:mm",

  /**
   * 格式化日期时间 (Date -> String)
   * @param datetime Date对象
   * @param fmt
   * @returns string
   */
  dateFormat: function (datetime, fmt) {
    if (!fmt)
      fmt = this.fmt_yyyy_MM_dd;
    if (!datetime) {
      return "";
    } else if (datetime instanceof Date) {
      let o = {
        "M+": datetime.getMonth() + 1,
        "d+": datetime.getDate(),
        "H+": datetime.getHours(),
        "m+": datetime.getMinutes(),
        "s+": datetime.getSeconds(),
        "S+": datetime.getMilliseconds()
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (datetime.getFullYear() + "").substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(String(o[k]).length)));
        }
      }
      return fmt;
    } else {
      return datetime;
    }
  },

  /*
   * 在js中String类型转成date格式 就是这么简单
   * var date = new Date("2018-9-21 14:58:43");
   */

  /**得到年月日*/
  getYMD: function () {
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var h = myDate.getHours();//获取当前小时数(0-23)
    var m = myDate.getMinutes();//获取当前分钟数(0-59)
    var s = myDate.getSeconds();//获取当前秒
    var week = myDate.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    // year + "年" + mon + "月" + date + "日" + weeks[week]
    return year + "年" + mon + "月" + date + "日";
  },

  /**得到年月日 时分秒*/
  getYMDHMS: function () {
    var myDate = new Date;
    var year = myDate.getFullYear(); //获取当前年
    var mon = myDate.getMonth() + 1; //获取当前月
    var date = myDate.getDate(); //获取当前日
    var h = myDate.getHours();//获取当前小时数(0-23)
    var m = myDate.getMinutes();//获取当前分钟数(0-59)
    var s = myDate.getSeconds();//获取当前秒
    var week = myDate.getDay();
    var weeks = ["星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
    // year + "年" + mon + "月" + date + "日" + weeks[week]
    return year + "年" + mon + "月" + date + "日 " + h + ":" + m + ":" + s;
  }
}


/**
 * 网络请求工具
 * @type {{request: appNet.request, post: appNet.post, postFile: appNet.postFile, get: appNet.get}}
 */
var ApiUtil = {
  post: function (url, token, params, async, loading, onResponseSuccess, onResponseCodeError, onError) {
    this.request(url, token, "post", params, async, null, loading, onResponseSuccess, onResponseCodeError, onError);
  },

  get: function (url, token, params, async, loading, onResponseSuccess, onResponseCodeError, onError) {
    this.request(url, token, "get", params, async, null, loading, onResponseSuccess, onResponseCodeError, onError);
  },

  /**
   * 接口请求
   * @param url
   * @param method
   * @param params
   * @param async
   * @param contentType
   * @param loading 是否显示加载中
   * @param onResponseSuccess
   * @param onResponseCodeError
   * @param onError
   */
  request: function (url, token, method, params, async, contentType, loading, onResponseSuccess, onResponseCodeError, onError) {
    //判断是否http和https开头，否则添加baseURL
    if (!/^http(s*):\/\//.test(url)) {
      url = API.baseUrl + url;
    }
    if (!contentType) {
      contentType = "application/x-www-form-urlencoded";
    }
    if (async == undefined) {
      async = false;
    }
    $.ajax({
      type: method,
      url: url,
      data: params,
      contentType: contentType,
      async: async,
      xhrFields: {withCredentials: true}, //支持跨域
      dataType: "json",
      timeout: 20000, //超时时间设置，单位毫秒
      beforeSend: function (request) {
        request.setRequestHeader("token", token);
        if (loading)
          vant.Toast.loading({
            duration: 0, // 持续展示
            forbidClick: true,
            message: '加载中...'
          });
      },

      success: function (res, status, xhr) {
        if (loading)
          vant.Toast.clear();
        if (res.code == 200) {
          if (onResponseSuccess)
            onResponseSuccess(res);
        } else {
          if (onResponseCodeError) {
            onResponseCodeError(res);
          }
          vant.Toast.fail(res.message ? res.message : "网络码异常");
          // vant.Notify({type: 'warning', message: res.result ? res.result : "网络码异常"});
        }
      },
      error: function (xhr) {
        if (loading)
          vant.Toast.clear();
        if (onError) {
          onError(xhr);
        }
        vant.Toast.fail('响应超时');
        // vant.Notify({type: 'danger', message: "网络异常"});
      }
    });
  },

  /**
   * 文件上传
   * @param url
   * @param params
   * @param onResponseSuccess
   * @param onResponseError
   * @param onError
   */
  postFile: function (url, params, loading, onResponseSuccess, onResponseError, onError) {
    if (!/^http(s*):\/\//.test(url))
      url = API.baseUrl + url;
    $.ajax({
      type: "post",
      url: url,
      data: params,
      async: true,
      processData: false,
      // contentType: "multipart/form-data",
      contentType: false,
      cache: false,
      xhrFields: {withCredentials: true}, //支持跨域
      dataType: "json",
      timeout: 60 * 1000, //超时时间
      beforeSend: function (xhr) {
        if (loading)
          vant.Toast.loading({
            duration: 0, // 持续展示
            forbidClick: true,
            message: '上传中...'
          });
      },
      success: function (res, status, xhr) {
        if (loading)
          vant.Toast.clear();
        if (res.success) {
          if (onResponseSuccess)
            onResponseSuccess(res);
        } else {
          if (onResponseError)
            onResponseError(res.result);
          else
          // vant.Notify({type: 'warning', message: res.result ? res.result : "上传失败"});
            vant.Toast.fail(res.result ? res.result : "上传失败");
        }
      },
      error: function (xhr) {
        if (loading)
          vant.Toast.clear();
        if (onError)
          onError(xhr);
        else
        // vant.Notify({type: 'danger', message: "上传错误"});
          vant.Toast.fail('上传错误');
      }
    });
  }
};



